package com.anita.member.application.service;

import com.anita.member.application.command.MemberRegisterCommand;
import com.anita.member.application.dto.MemberRegisterResponse;
import com.anita.member.application.port.in.MemberRegisterUseCase;
import com.anita.member.common.exception.BusinessException;
import com.anita.member.domain.model.member.*;
import com.anita.member.domain.repository.MemberRepository;
import com.anita.member.common.enums.Resp;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author qiu
 * @date 2025/10/17
 * @description
 */
@Slf4j
@Service
@Transactional
public class MemberRegisterService implements MemberRegisterUseCase {

    @Resource
    private MemberRepository memberRepository;

    @Resource
    private PasswordEncoder passwordEncoder;

    /**
     * 会员注册
     * @param command
     * @return
     */
    public MemberRegisterResponse registerMember(MemberRegisterCommand command) {
        //验证会员用户名是否存在
        Username username = Username.of(command.username());
        if(memberRepository.existsByUsername(username)){
            throw new BusinessException(Resp.USER_NAME_ALREADY_EXISTS);
        }

        //验证手机号是否存在
        Phone phone = Phone.of(command.phone());
        if(memberRepository.existsByPhone(phone)){
            throw new BusinessException(Resp.USER_PHONE_ALREADY_EXISTS);
        }

        //验证邮箱是否存在
        Email email = Email.of(command.email());
        if(memberRepository.existsByEmail(email)){
            throw new BusinessException(Resp.USER_EMAIL_ALREADY_EXISTS);
        }

        //创建密码
        Password password = Password.fromRaw(command.password(), passwordEncoder);

        //创建会员聚合根
        Member member = new Member(
                MemberId.generate(),
                username,
                Nickname.of(command.nickname()),
                password,
                phone,
                email,
                Avatar.of(command.avatar())
        );

        //保存会员
        Member savedMember = memberRepository.save(member);

        log.info("会员注册成功，{}",savedMember.getUserName().getValue());

        return new MemberRegisterResponse(
                savedMember.getId().value(),
                savedMember.getUserName().getValue(),
                savedMember.getNickName().getValue(),
                savedMember.getPhone().getValue(),
                savedMember.getEmail().getValue(),
                savedMember.getAvatar().value()
        );
    }

}
